package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;
import java.io.PrintWriter;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();

        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            handler = new DefaultHandler();
        }

        if (handler != null) {
            handler.handle(request, response);
        } else {
            PrintWriter writer = new PrintWriter(response);
            String errorContent = "<h1>500 Internal Server Error</h1><p>No handler available for this request.</p>";

            writer.println("HTTP/1.1 500 Internal Server Error");
            writer.println("Content-Type: text/html; charset=UTF-8");
            writer.println("Content-Length: " + errorContent.getBytes().length);
            writer.println("Connection: close");
            writer.println();
            writer.println(errorContent);
            writer.flush();
        }
    }
}
